/**
 * 品牌
 * 文件命名格式：zmn.模块名称.表名称.功能.jas
 * @author duanzucai
 * @since 2018/11/10
 */
layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'laydate','jquery'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laypage = layui.laypage;
    var layedit = layui.layedit;
    var laydate = layui.laydate;
    let faultGroupVOList =json.productFaultGroupVOList;

    layui.form.render();

    let flag = layui.$('#showAllItems').is(':checked');

    if(faultGroupVOList&&faultGroupVOList.length>0){
        faultGroupVOList.forEach(e=>{
            table.init('zmn-table'+e.groupId, {
                page: false,
                limit: 100000,
                done:function (res) {
                    let table = layui.$('#zmn-table'+e.groupId).next("div").find('table');
                    layui.$('#zmn-table'+e.groupId).next('div').find('.layui-table-fixed-l tbody tr');
                    let checkBoxes = table.find('td[data-field="status"]');
                    checkBoxes.each(function (i,item) {
                        let tr = layui.$(item).parents("tr");
                        let data_index = layui.$(tr).attr('data-index');
                        let priceStandard = tr.find('td[data-field="priceStandard"] div').html();
                        let itemChecked = layui.$(item).find('input').attr('checked');
                        if (flag) {
                            layui.$(tr).show();
                            layui.$('#zmn-table'+e.groupId).next('div').find('.layui-table-fixed-l tbody tr[data-index=' + data_index + ']').show();
                            layui.$('#zmn-table'+e.groupId).next('div').find('.layui-table-fixed-r tbody tr[data-index=' + data_index + ']').show();
                        } else {
                            if (itemChecked != 'checked') {
                                layui.$(tr).hide();
                                layui.$('#zmn-table'+e.groupId).next('div').find('.layui-table-fixed-l tbody tr[data-index=' + data_index + ']').hide();
                                layui.$('#zmn-table'+e.groupId).next('div').find('.layui-table-fixed-r tbody tr[data-index=' + data_index + ']').hide();
                            }
                        }

                        let price = tr.find('td[data-field="price"]');
                        let internalSettlementPrice = tr.find('td[data-field="internalSettlementPrice"]');
                        let externalSettlementPrice = tr.find('td[data-field="externalSettlementPrice"]');
                        if(json.productFaultTariff.status==2){
                            layui.$(item).find('input').prop("disabled", false);
                            layui.$(item).find('input').next('div').removeClass('layui-disabled')
                        } else{
                            layui.$(item).find('input').prop("disabled", true);
                            layui.$(item).find('input').next('div').addClass('layui-disabled')
                        }
                        if(json.productFaultTariff.status==2&&itemChecked=='checked'){
                            if(priceStandard == '一口价'){
                                let tdPrice =  layui.$(price).data("edit",true).removeClass('layui-disabled').prop("disabled", false);
                                tdPrice.find("input").prop("disabled", false).removeClass("text-disabled").addClass("text-enable");
                                let tdInternalSettlementPrice = layui.$(internalSettlementPrice).data("edit",true).removeClass('layui-disabled').prop("disabled", false);
                                tdInternalSettlementPrice.find("input").prop("disabled", false).removeClass("text-disabled").addClass("text-enable");
                                let tdExternalSettlementPrice = layui.$(externalSettlementPrice).data("edit",true).removeClass('layui-disabled').prop("disabled", false);
                                tdExternalSettlementPrice.find("input").prop("disabled", false).removeClass("text-disabled").addClass("text-enable");
                            }else{
                                let tdPrice =  layui.$(price).data("edit",false).removeClass('layui-disabled').prop("disabled", false);
                                tdPrice.find("input").prop("disabled", false).removeClass("text-disabled").addClass("text-enable");
                                let tdInternalSettlementPrice = layui.$(internalSettlementPrice).data("edit",false).addClass('layui-disabled').prop("disabled", true);
                                tdInternalSettlementPrice.find("input").prop("disabled", true).removeClass("text-enable").addClass("text-disabled");
                                let tdExternalSettlementPrice = layui.$(externalSettlementPrice).data("edit",false).addClass('layui-disabled').prop("disabled", true);
                                tdExternalSettlementPrice.find("input").prop("disabled", true).removeClass("text-enable").addClass("text-disabled");
                            }

                        }else{
                            let tdPrice = layui.$(price).data("edit",false).addClass('layui-disabled').prop("disabled", true);
                            tdPrice.find("input").prop("disabled", true).removeClass("text-enable").addClass("text-disabled");
                            let tdInternalSettlementPrice = layui.$(internalSettlementPrice).data("edit",false).addClass('layui-disabled').prop("disabled", true);
                            tdInternalSettlementPrice.find("input").prop("disabled", true).removeClass("text-enable").addClass("text-disabled");
                            let tdExternalSettlementPrice = layui.$(externalSettlementPrice).data("edit",false).addClass('layui-disabled').prop("disabled", true);
                            tdExternalSettlementPrice.find("input").prop("disabled", true).removeClass("text-enable").addClass("text-disabled");
                        }

                    });
                }
            });
        });
    }

    //监听指定开关
    form.on('switch(switchTest)', function(data){
        // 显示全部项目开关
        let flag = this.checked;
        let tables = layui.$('.table-filter');
        tables.each(function (i,item) {
            let id = tables[i].id;
            let table = layui.$('#'+id).next("div").find('table');
            // let table = layui.$(item).next("div").find('table');
            let checkBoxes = table.find('td[data-field="status"]');
            checkBoxes.each(function (i,item) {
                let tr = layui.$(item).parents("tr");
                let data_index = layui.$(tr).attr('data-index');
                let itemChecked = layui.$(item).find('input').attr('checked');
                if (flag) {
                    layui.$(tr).show();
                    layui.$('#'+id).next('div').find('.layui-table-fixed-l tbody tr[data-index=' + data_index + ']').show();
                    layui.$('#'+id).next('div').find('.layui-table-fixed-r tbody tr[data-index=' + data_index + ']').show();
                } else {
                    if (itemChecked != 'checked') {
                        layui.$(tr).hide();
                        layui.$('#'+id).next('div').find('.layui-table-fixed-l tbody tr[data-index=' + data_index + ']').hide();
                        layui.$('#'+id).next('div').find('.layui-table-fixed-r tbody tr[data-index=' + data_index + ']').hide();
                    }
                }
            });
        });
    });

    form.on('radio(status)', function (data) {
        let value = data.value;
        if (json.general == 2 && value == 1){
            return layer.msg("默认产品价格表不能被停用",{time: 1000},function () {
                window.location.reload();
            });
        }

        let id = json.productFaultTariff.relateId;
        let obj = new Object();
        if (value == 1){
            obj['event'] = 'stop';
        } else {
            obj['event'] = 'start';
        }

        zmnPage.layStartStop(obj, "/product/tariff/updateStatus.action", id);
    });

    form.on('checkbox(status)', function(data){
        let tr = $(this).parents("tr");
        let priceStandard = tr.find('td[data-field="priceStandard"]');
        let price = tr.find('td[data-field="price"]');
        let internalSettlementPrice = tr.find('td[data-field="internalSettlementPrice"]');
        let externalSettlementPrice = tr.find('td[data-field="externalSettlementPrice"]');
        let priceStandardValue = $(priceStandard).find('div').text();
        //价格表状态可用，一口价，只有一个框
        if(json.productFaultTariff.status==2 && data.elem.checked){
            if(priceStandardValue == '一口价'){
                let tdPrice = $(price).data("edit",true).removeClass('layui-disabled').prop("disabled", false);
                tdPrice.find("input").prop("disabled", false).removeClass("text-disabled").addClass("text-enable");
                let tdInternalSettlementPrice = $(internalSettlementPrice).data("edit",true).removeClass('layui-disabled').prop("disabled", false);
                tdInternalSettlementPrice.find("input").prop("disabled", false).removeClass("text-disabled").addClass("text-enable");
                let tdExternalSettlementPrice = $(externalSettlementPrice).data("edit",true).removeClass('layui-disabled').prop("disabled", false);
                tdExternalSettlementPrice.find("input").prop("disabled", false).removeClass("text-disabled").addClass("text-enable");
            }else{
                let tdPrice = $(price).removeClass('layui-disabled').prop("disabled", false);
                tdPrice.find("input").prop("disabled", false).removeClass("text-disabled").addClass("text-enable");
                let tdInternalSettlementPrice = $(internalSettlementPrice).data("edit",false).addClass('layui-disabled').prop("disabled", true);
                tdInternalSettlementPrice.find("input").prop("disabled", true).removeClass("text-enable").addClass("text-disabled");
                let tdExternalSettlementPrice = $(externalSettlementPrice).data("edit",false).addClass('layui-disabled').prop("disabled", true);
                tdExternalSettlementPrice.find("input").prop("disabled", true).removeClass("text-enable").addClass("text-disabled");
            }
        }else{
            let tdPrice = $(price).data("edit",false).addClass('layui-disabled').prop("disabled", true);
            tdPrice.find("input").prop("disabled", true).removeClass("text-enable").addClass("text-disabled");
            let tdInternalSettlementPrice = $(internalSettlementPrice).data("edit",false).addClass('layui-disabled').prop("disabled", true);
            tdInternalSettlementPrice.find("input").prop("disabled", true).removeClass("text-enable").addClass("text-disabled");
            let tdExternalSettlementPrice = $(externalSettlementPrice).data("edit",false).addClass('layui-disabled').prop("disabled", true);
            tdExternalSettlementPrice.find("input").prop("disabled", true).removeClass("text-enable").addClass("text-disabled");
        }

        form.render();
    });


    function deleteComma(data){
        for (var j = 0; j < data.length; j++){
            if (data[j]['price'] != undefined) {
                data[j]['price'] = data[j]['price'].replace(/,/g, "").replace(/\s*/g,"");
            }
            if (data[j]['negotiableMinPrice'] != undefined) {
                data[j]['negotiableMinPrice'] = data[j]['negotiableMinPrice'].replace(/,/g, "").replace(/\s*/g,"");
            }
            if (data[j]['negotiableMaxPrice'] != undefined) {
                data[j]['negotiableMaxPrice'] = data[j]['negotiableMaxPrice'].replace(/,/g, "").replace(/\s*/g,"");
            }
            if (data[j]['internalSettlementPrice'] != undefined) {
                data[j]['internalSettlementPrice'] = data[j]['internalSettlementPrice'].replace(/,/g, "").replace(/\s*/g,"");
            }
            if (data[j]['externalSettlementPrice'] != undefined) {
                data[j]['externalSettlementPrice'] = data[j]['externalSettlementPrice'].replace(/,/g, "").replace(/\s*/g,"");
            }
            if (data[j]['partPrice'] != undefined) {
                data[j]['partPrice'] = data[j]['partPrice'].replace(/,/g, "").replace(/\s*/g,"");
            }
            if (data[j]['servicePrice'] != undefined) {
                data[j]['servicePrice'] = data[j]['servicePrice'].replace(/,/g, "").replace(/\s*/g,"");
            }
        }
    }

    // 提交
    form.on('submit(zmn-form-submit)', function(obj){
        let innerArr = new Array();
        var flag = false;
        if(faultGroupVOList&&faultGroupVOList.length>0){
            for(var i = 0; i < faultGroupVOList.length; i++){
                let id = 'zmn-table'+faultGroupVOList[i].groupId;
                var data = layui.table.cache[id];
                deleteComma(data);
                flag = false;
                let table = $("#"+id).next("div").find('table');
                for (var j = 0; j < data.length; j++){
                    let inner = new Object();
                    inner['keepType'] = faultGroupVOList[i].keepType;
                    inner['productId'] = faultGroupVOList[i].productId;
                    inner['tariffId'] = faultGroupVOList[i].tariffId;
                    inner['groupId'] = faultGroupVOList[i].groupId;

                    let statusDiv = table.find("tr:eq("+j+") :checkbox").next("div");
                    let status=1;
                    if(statusDiv.hasClass('layui-form-checked')){
                        status = 2;
                    }
                    if (status == 1){
                        continue;
                    }
                    inner['status'] = status;
                    //非一口价不存在price
                    let price = table.find("tr:eq("+j+") input[name=price]")[0];
                    if(price){
                        price=price.value.trim();
                        price = price.replace(/,/g, "");
                    }
                    let itemId = data[j].itemId;
                    let internalSettlementPrice =  table.find("tr:eq("+j+") input[name=internalSettlementPrice]")[0];
                    let externalSettlementPrice =  table.find("tr:eq("+j+") input[name=externalSettlementPrice]")[0];
                    if(internalSettlementPrice){
                        internalSettlementPrice=internalSettlementPrice.value.trim();
                        internalSettlementPrice = internalSettlementPrice.replace(/,/g, "");
                    }
                    if(externalSettlementPrice){
                        externalSettlementPrice=externalSettlementPrice.value.trim();
                        externalSettlementPrice = externalSettlementPrice.replace(/,/g, "");
                    }

                    let trafficFee = data[j].trafficFee;
                    let hourFee = data[j].hourFee;
                    let checkFee = data[j].checkFee;
                    let partRatio = data[j].partRatio;
                    let artRatio = data[j].artRatio;
                    let guaranteeRatio = data[j].guaranteeRatio;
                    let priceSplit = data[j].priceSplit;
                    let priceStandard = data[j].priceStandard;
                    //面议价格范围，可以为空，必须是数字，二者要么都为空，要么都必填，两个不为空有范围限制
                    inner['negotiableMinPrice'] = '';
                    inner['negotiableMaxPrice'] = '';
                    if(priceStandard == '非一口价'){
                        let negotiableMinPrice = table.find("tr:eq("+j+") input[name=negotiableMinPrice]")[0].value;
                        if (negotiableMinPrice != undefined) {
                            negotiableMinPrice = negotiableMinPrice.replace(/,/g, "");
                        }
                        let negotiableMaxPrice = table.find("tr:eq("+j+") input[name=negotiableMaxPrice]")[0].value.replace(/,/g, "");
                        if (negotiableMaxPrice != undefined) {
                            negotiableMaxPrice = negotiableMaxPrice.replace(/,/g, "");
                        }

                        if(negotiableMinPrice){
                            negotiableMinPrice = negotiableMinPrice .trim();
                        }
                        if(negotiableMaxPrice){
                            negotiableMaxPrice = negotiableMaxPrice .trim();
                        }
                        //只填写了一个
                        if((!negotiableMinPrice&&negotiableMaxPrice)||(negotiableMinPrice&&!negotiableMaxPrice)){
                            layer.alert("服务项ID为"+itemId+"的服务项的销售价价格区间必须同时填写或者都不填写");
                            flag = true;
                            break;
                        }
                        //二者都填写
                        if(negotiableMinPrice&&negotiableMaxPrice){
                            let reg=/^\d+(\.\d{1,2})?$/;
                            if(!reg.test(negotiableMinPrice)||!reg.test(negotiableMaxPrice)){
                                layer.alert("服务项ID为"+itemId+"的服务项的销售价价格区间只能填写正数(整数或者两位小数)");
                                flag = true;
                                break;
                            }
                            let max = negotiableMaxPrice*100;
                            let min = negotiableMinPrice*100;
                            if(max<=min){
                                layer.alert("服务项ID为"+itemId+"的服务项的销售价价格区间右侧必须大于左侧");
                                flag = true;
                                break;
                            }
                            inner['negotiableMinPrice'] = min;
                            inner['negotiableMaxPrice'] = max;
                        }
                    }


                    if (!verify(price)){
                        layer.alert("服务项ID为"+itemId+"的服务项的销售价格式错误:应输入正整数或者两位小数,且最大值不超过1000000");
                        flag = true;
                        break;
                    }
                    if (!verify(internalSettlementPrice)){
                        layer.alert("服务项ID为"+itemId+"的服务项的内部结算价格式错误:应输入正整数或者两位小数,且最大值不超过1000000");
                        flag = true;
                        break;
                    }
                    if (!verify(externalSettlementPrice)){
                        layer.alert("服务项ID为"+itemId+"的服务项的外部结算价格式错误:应输入正整数或者两位小数,且最大值不超过1000000");
                        flag = true;
                        break;
                    }
                    if (priceStandard == '一口价' && status == 2){
                        if (price == null || price == ''){
                            layer.alert("服务项ID为"+itemId+"的服务项的销售价格式为必填项");
                            flag = true;
                            break;
                        }
                    }
                    if (priceSplit == '区分' && partRatio != undefined && partRatio != null && partRatio != ''
                        && price != null && price != ''){
                        let total = (parseFloat(trafficFee) + parseFloat(hourFee) + parseFloat(checkFee)) / ((100 - partRatio-artRatio-guaranteeRatio) / 100);
                        //只如不舍，保留两位
                        total = Math.ceil(total*100)/100;
                        if (price < total){
                            layer.alert("服务项ID为"+itemId+"的服务项的销售价必须大于或者等于"+total);
                            flag = true;
                            break;
                        }
                    }
                    inner['itemId'] = data[j].itemId;
                    inner['sort'] = data[j].sort;
                    if (price == null || price == ''){
                        inner['price'] = "";
                    } else {
                        inner['price'] = accMul(price, 100);
                    }

                    if (internalSettlementPrice == null || internalSettlementPrice == ''){
                        inner['internalSettlementPrice'] = "";
                    } else{
                        inner['internalSettlementPrice'] = accMul(internalSettlementPrice, 100);
                    }

                    if (externalSettlementPrice == null || externalSettlementPrice == ''){
                        inner['externalSettlementPrice'] = "";
                    } else{
                        inner['externalSettlementPrice'] = accMul(externalSettlementPrice, 100);
                    }

                    if (priceSplit == '区分' && partRatio != undefined && partRatio != null && partRatio != ''
                        && price != null && price != ''){
                        var partPrice = accMul(price, partRatio);
                        inner['partPrice'] = partPrice;
                        inner['servicePrice'] = accMul(price, 100) - accMul(trafficFee, 100) - accMul(hourFee, 100) - partPrice;
                    } else {
                        inner['partPrice'] = "";
                        inner['servicePrice'] = "";
                    }

                    if (status == 2){
                        innerArr.push(inner);
                    }
                }

                if (flag){
                    break;
                }
            }
        }

        if (flag){
            return false;
        }
        if (innerArr.length <= 0){
            return layer.msg("请填写相应数据后再提交！");
        }

        var data = innerArr;
        var url = "/product/tariff/item/batchAddEdit.action";

        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(data),
            success:function(rs) {
                if (rs.status === 200) {
                    parent.layui.layer.msg(rs.message,{time: 1000},()=>{
                        window.location.reload();
                        return true;
                    });
                }else {
                    parent.layui.layer.msg(rs.message,{"icon":2});
                    return false;
                }
            }
        })
        return false;
    });

    exports('serv_product_tariff_group_list', {});
});

function verify(testValue) {
    var reg=/^\d+(\.\d{1,2})?$/;

    if (testValue != null && testValue != undefined && testValue != ""){
        if(!reg.test(testValue))
        {
            // layer.alert("请输入整数或者1到2位小数");
            return false;
        }

        if (testValue == '0' || testValue == '0.0' || testValue == '0.00'){
            return false;
        }

        let value = parseFloat(testValue);
        if (0 < value&&value <= 1000000){
        } else{
            // layer.alert("最大值为1000000，请调整后再试");
            return false;
        }
    }

    return true;
}

function reload(msg){
    parent.layui.layer.msg(msg);
    window.location.reload();
}

/**
 * 描述: 新增/修改产品分类名称
 **/
function setPrice(itemId,productId){
    zmnLayUtil.openIframeCustom(layer, "/product/tariff/tariffproductitem3/setPrice.action?serviceItemId="+itemId+"&productId="+productId, {title: "设置基础价格", shade: 0.8, area:["80%", "80%"]});
}
function cancel() {
    window.location.href="/product/tariff/list.action?flag=4&tariffId="+json.tariffId;
}

/**
 * 描述: 跳转到城市价格设置页面
 **/
function toCityPrice(productId, tariffId, groupId, itemId, priceStandard){
    if (productId == null && tariffId == null) {
        layui.layer.msg("请先勾选项目并保存，再设置城市价格");
        return;
    }
    zmnLayUtil.openTabsPageCustom(parent, "/product/tariff/item/city/price/list.action?productId="+productId+"&tariffId="+tariffId+"&groupId="+groupId+"&itemId="+itemId+"&priceStandard="+priceStandard, "城市价格");
}

/**
 * 精度保留两位小数：四舍五入
 */
function accMul(arg1,arg2)
{
    var m=0,s1=arg1.toString(),s2=arg2.toString();
    try{m+=s1.split(".")[1].length}catch(e){}
    try{m+=s2.split(".")[1].length}catch(e){}
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
}
